#!/usr/bin/env bash

## This Source Code Form is subject to the terms of the Mozilla Public
## License, v. 2.0. If a copy of the MPL was not distributed with this
## file, You can obtain one at http://mozilla.org/MPL/2.0/.

if [ -n "$SKIP_CHECK" ]; then
  echo "Skipping checks"
  exit 0
fi

if [ -z "$srcdir" ]; then
  srcdir="./"
fi

if [ -z "$tmpdir" ]; then
  tmpdir="/tmp"
fi

if [ -z "$builddir" ]; then
  builddir="./"
fi

# We only print using colors if the output is going to a terminal
if [ -t 1 ] ; then
  NC='\033[0m'
  RED='\033[1;31m'
  GREEN='\033[1;32m'
  YELLOW='\033[1;33m'
  PINK='\033[1;35m'
fi

workdir=$(mktemp -d ${tmpdir}/libxc.XXXXXXXXXX)

fail=0
echo -e "${YELLOW}Comparing against reference data${NC}"
echo -e "Using ${workdir} as working directory"
echo -e "========================================================================="
echo -e "   Functional                    System      NSpin   Quantity    Result"
echo -e "========================================================================="

for dir in $(ls -d $srcdir/regression/*); do
  for i in $(ls $dir/*.bz2 | LANG=C sort); do
    refname=$(basename ${i} .bz2)
    func=${refname%%.*}
    #if [ $func != "gga_x_wpbeh" ]; then
    #  continue
    #fi
    testcase=${refname#*.}
    system=${testcase%%.*}
    order=${testcase##*.}
    if [ "x${testcase#*.}" = "xunpol.$order" ]; then
      nspin=1
    else
      nspin=2
    fi
    case $order in
    0)
      label=exc
      tol=5e-8
      ;;
    1)
      label=vxc
      tol=5e-5
      ;;
    2)
      label=fxc
      tol=5e-4
      ;;
    esac
    name=$(printf '%-30s %-12s %-8d %-5s' ${func} ${system} ${nspin} ${label})
  
    echo -ne "${NC} * ${PINK}${name}"

    bunzip2 -c $dir/$refname.bz2 > $workdir/${refname}_ref

    $EXEC $builddir/xc-regression $func $nspin $order $srcdir/input/$system $workdir/$refname > /dev/null
  
    res=$($builddir/xc-error $workdir/$refname $workdir/${refname}_ref $tol)
    if [ "x$res" = "x1" ]; then
      echo -e "      ${GREEN}OK"
      rm $workdir/$refname $workdir/${refname}_ref
    else
      echo -e "     ${RED}FAIL"
      let fail++
    fi
  done
done
echo -e "${NC}"

exit $fail
